<?php
/*************************************************************************************
   Copyright notice

   This script uses some code parts of the glossary module for phpwcms (c) Oliver Georgi
   (c) 2002-2009 Oliver Georgi (oliver@phpwcms.de) // All rights reserved.

   This script uses some code parts from bmcatalog module
   (c) 2010 Benjamin Matzmorr, www.etype.de

   (c) 2012 webrealisierung gmbh, www.webrealisierung.ch
   Catalogue Module V 1.0.0  -  Date: 2012-06-01

   The GNU General Public License can be found at http://www.gnu.org/copyleft/gpl.html
   A copy is found in the textfile GPL.txt and important notices to the license
   from the author is found in LICENSE.txt distributed with these scripts.

   This script is distributed in the hope that it will be useful, but WITHOUT ANY
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
   PARTICULAR PURPOSE.  See the GNU General Public License for more details.

   This copyright notice MUST APPEAR in all copies of the script!
*************************************************************************************/
// ----------------------------------------------------------------
// obligate check for phpwcms constants
if (!defined('PHPWCMS_ROOT')) {
   die("You Cannot Access This Script Directly, Have a Nice Day.");
}
// ----------------------------------------------------------------

require_once (MODULE_CTG_PATH.'inc/ctg.front.func.inc.php');
require_once (PHPWCMS_ROOT.'/include/inc_ext/feedcreator/feedcreator.class.php');

  $plugin_ctg['feeds_formats']	= array('0.91', 'RSS0.91', '1.0', 'RSS1.0', '2.0', 'RSS2.0', 'ATOM', 'ATOM1.0', 'ATOM0.3');

  $artID = intval($_GET['art_id']);
  $cpID = intval($_GET['cp_id']);

  $plugin_ctg['sql_cp']  = "SELECT * FROM ".DB_PREPEND."phpwcms_articlecontent WHERE acontent_aid=".$artID." AND acontent_id=".$cpID."";
	$plugin_ctg['data_cp']   = _dbQuery($plugin_ctg['sql_cp'] );
		
	foreach($plugin_ctg['data_cp'] as $crow) {
      $content['br_catalogue']	= unserialize($crow["acontent_form"]); //should be only one
  }

  $plugin_ctg['feeds'] 			= array();
  $plugin_ctg['feeds']['default'] = array(
								"title"				=> $content['br_catalogue']['ctg_rss_title'],
								"description"		=> $content['br_catalogue']['ctg_rss_descr'],
								"link"				=> PHPWCMS_URL,
								"syndicationURL"	=> "",
								"imagesrc"			=> "",
								"imagetitle"		=> "",
								"imagelink"			=> "",
								"imagedescription"	=> "",
								"timeZone"			=> "+01:00",
								"cacheTTL"			=> 3600,
								"structureID"		=> "",
								"useauthor"			=> 1,
								"feedAuthor"		=> "",
								"maxentries"		=> $content['br_catalogue']['ctg_rss_number'],
								"encoding"			=> "UTF-8",
								"defaultFormat"		=> "RSS2.0",
								"filename"			=> "default_feed.xml",
                "locale"   =>  "de_DE",
                "dateformat"   =>  "%A, %d. %B %Y"
							  );

  if( count($content['br_catalogue']['ctg_catalogs']) ) {
  //we update even if in CP it could beinactive ??

    $CTG_FEED = $plugin_ctg['feeds']['default'];
    $CTG_FEED['defaultFormat']	= empty($_GET['format']) ? trim($CTG_FEED['defaultFormat']) : strtoupper(clean_slweg($_GET['format']));
    $CTG_FEED['defaultFormat']	= in_array($CTG_FEED['defaultFormat'], $plugin_ctg['feeds_formats']) ? $CTG_FEED['defaultFormat'] : "RSS2.0";
    $CTG_FEED['filename']		=  CONTENT_PATH.'rss/feed-catalog-'.$artID.'-'.$cpID.'.xml';
    $CTG_FEED['maxentries']		= intval($CTG_FEED['maxentries']);
    $CTG_FEED['useauthor']		= intval($CTG_FEED['useauthor']);
    $CTG_FEED['encoding']		= empty($CTG_FEED['encoding']) ? 'utf-8' : $CTG_FEED['encoding'];

    define('FEED_ENCODING', trim(strtolower($CTG_FEED['encoding'])));
    define("TIME_ZONE","+01:00");

    $rss 						= new UniversalFeedCreator();
    //$rss->useCached($CTG_FEED['defaultFormat'], $CTG_FEED['filename'], intval($CTG_FEED['cacheTTL']));
    $rss->title 				= cm_combinedParser($CTG_FEED['title'], FEED_ENCODING);
    $rss->description 			= cm_combinedParser($CTG_FEED['description'], FEED_ENCODING);
    $rss->link 					= $CTG_FEED['link'];
    $rss->syndicationURL 		= $CTG_FEED['syndicationURL'];
    $rss->encoding				= FEED_ENCODING;
    if(!empty($CTG_FEED['feedAuthor'])) {
    	$rss->editor			= $CTG_FEED['feedAuthor'];
    }
    if(!empty($CTG_FEED['feedEmail'])) {
    	$rss->editorEmail		= $CTG_FEED['feedEmail'];
    }

    if(!empty($CTG_FEED['imagesrc'])) {

    	$image 					= new FeedImage();
    	$image->title 			= cm_combinedParser($CTG_FEED['imagetitle'], FEED_ENCODING);
    	$image->url 			= $CTG_FEED['imagesrc'];
    	$image->link			= $CTG_FEED['imagelink'];
    	$image->description		= cm_combinedParser($CTG_FEED['imagedescription'], FEED_ENCODING);
    	$rss->image 			= $image;

    }

    //build the sql for active catalogs ...
  $plugin_ctg['catarray'] = array();
    foreach($content['br_catalogue']['ctg_catalogs']	 as $val) {
        $plugin_ctg['catarray'][] = "ctge_catalogid LIKE '%|".aporeplace(intval($val))."|%'";
  	}
    $plugin_ctg['wherequery'] = (count($plugin_ctg['catarray'])) ? " AND (".implode(' OR ', $plugin_ctg['catarray']).")" : " AND bmc_allcats = '0'"; //then statement is never true

    //get events
    $plugin_ctg["sql"]  = 'SELECT * FROM '.DB_PREPEND.'phpwcms_mod_catalogue_entry WHERE ';
  	$plugin_ctg["sql"] .= "ctge_status = 1";
  	$plugin_ctg["sql"] .= $plugin_ctg['wherequery'];
  	$plugin_ctg["sql"] .= " ORDER BY ctge_title";

    if($CTG_FEED['maxentries']) {
    	$plugin_ctg["sql"] .= " LIMIT ".$CTG_FEED['maxentries'];
    }
    $plugin_ctg["data"] = _dbQuery($plugin_ctg["sql"]);

    //prepare output
    $plugin_ctg["timeplus"] = 0;
  	if( !isset($plugin_ctg["data"][0]) ) {
      $plugin_ctg["output"]		= '\n'; //no entry
    } else {  
      foreach ($plugin_ctg["data"] as $value) {
  	    $value['ctge_entry_image'] = unserialize(	$value['ctge_image']);

    		$item = new FeedItem();
    		$item->title 			= cm_combinedParser($value['ctge_title'], FEED_ENCODING);
    		$item->link 			= PHPWCMS_URL.'index.php?aid='.$artID.'&ctg_id='.$value['ctge_id'];
        setlocale(LC_TIME, $CTG_FEED['locale'].".UTF-8");
        $desr =  cm_combinedParser( $value['ctge_title2'] , FEED_ENCODING)."<br />";
        $desr .=  cm_combinedParser( $value['ctge_text'] , FEED_ENCODING)."<br />";
        $desr .=   cm_combinedParser( empty($value['ctge_text2']) ? '' : $value['ctge_text2'] , FEED_ENCODING)  ;
    		$item->description 		= $desr;
    		$item->date 			= strtotime($value['ctge_changed']) + $plugin_ctg["timeplus"];
        $item->updateDate		= strtotime($value['ctge_changed'])  + $plugin_ctg["timeplus"] + 1;

        //image
        if( !empty($value['ctge_entry_image'][0]['ctge_images'][0]) && $value['ctge_entry_image'][0]['active'] == 1  ) { //phpwcms image

  		    $plugin_ctg["sql_img"] = 'SELECT * FROM '.DB_PREPEND.'phpwcms_file WHERE f_aktiv=1 AND f_public=1 AND f_id='.$value['ctge_entry_image'][0]['ctge_images'][0];
  		    $plugin_ctg["data_img"] = _dbQuery($plugin_ctg["sql_img"]);

          if(isset($plugin_ctg["data_img"][0])) {
            $plugin_ctg["thumbsize"] = @getimagesize(PHPWCMS_FILES.$plugin_ctg["data_img"][0]["f_hash"] . '.' . $plugin_ctg["data_img"][0]["f_ext"]);

           $plugin_ctg["item_img"]	 = get_cached_image(
  						array(	"target_ext"	=>	$plugin_ctg["data_img"][0]["f_ext"],
  								"image_name"	=>	$plugin_ctg["data_img"][0]["f_hash"] . '.' . $plugin_ctg["data_img"][0]["f_ext"],
  								"max_width"		=>	$plugin_ctg["thumbsize"][0],
  								"max_height"	=>	$plugin_ctg["thumbsize"][1],
  								"thumb_name"	=>	md5(	$plugin_ctg["data_img"][0]["f_hash"].$plugin_ctg["thumbsize"][0].
  															$plugin_ctg["thumbsize"][1].$GLOBALS['phpwcms']["sharpen_level"])
  						)
          	);

          //<enclosure url="http://example.com/image.jpg" length="12216320" type="images/jpeg" />
          //$item->enclosure
          $item->enclosure->url = PHPWCMS_URL.PHPWCMS_IMAGES.$plugin_ctg["item_img"][0];
          $item->enclosure->length = filesize(PHPWCMS_ROOT.'/'.PHPWCMS_IMAGES.$plugin_ctg["item_img"][0]);
          $item->enclosure->type = "images/jpeg";
        }
      } else if ($value['ctge_entry_image'][1]['active'] == 1) { //img from folder

          $plugin_ctg["imgfolder"] = opendir(MODULE_CTG_PATH.$value['ctge_entry_image'][1]['root']);

          $plugin_ctg["pic_types"] = array("jpg", "jpeg", "gif", "png");
          $plugin_ctg["folderpics"] = array();
          while ($file = readdir ($plugin_ctg["imgfolder"])) {
            if(in_array(substr(strtolower($file), strrpos($file,".") + 1),$plugin_ctg["pic_types"]) ) {
              array_push($plugin_ctg["folderpics"],$file);
            }
          }
          closedir($plugin_ctg["imgfolder"]);
          if (count($plugin_ctg["folderpics"])) {
            $item->enclosure->url = PHPWCMS_URL.MODULE_CTG_DIR.$value['ctge_entry_image'][1]['root'].$plugin_ctg["folderpics"][0];
            $item->enclosure->length = filesize(PHPWCMS_ROOT.'/'.MODULE_CTG_DIR.$value['ctge_entry_image'][1]['root'].$plugin_ctg["folderpics"][0]);
            $item->enclosure->type = "images/jpeg";
          }

      } //end imgage

  		$item->source 			= PHPWCMS_URL;
  		if($CTG_FEED['useauthor'] || $CTG_FEED['defaultFormat'] == 'ATOM' || $CTG_FEED['defaultFormat'] == 'ATOM1.0') {
  				$item->author 	= $CTG_FEED['feedAuthor'];
  		}
  		$item->guid				= PHPWCMS_URL.'index.php?aid='.$artID.'&ctg_id='.$value['ctge_id'];
  		$rss->addItem($item);
		  $plugin_ctg["timeplus"] += 2;
      }  //end foreach
    }//end if data

    //write the xml file
    $rss->saveFeed($CTG_FEED['defaultFormat'], $CTG_FEED['filename'], false);
  }
  unset($plugin_ctg);
  //redirect to CP-tab
  headerRedirect(decode_entities(ctg_map_url('controller=module')));

?>